<template>
<!--  <div class="container">-->
    <div class="video-container" ref="videoContainerRef" @click="handleVideoClick">
      <!-- Four img tags to display the video streams -->

      <div v-if="isVideoAvailable" class="video-wrapper">
        <img class="video-stream" :src="videoSrc2"  @click="handleVideoClick($event)" />
      </div>
      <div v-else class="video-placeholder">
        <div >
          <div class="loader"></div>
          <h2 style="color: white">Loading...</h2>
        </div>
      </div>
      <div v-for="position in clickPositions" class="dot" :style="{ top: position.y + 'px', left: position.x + 'px' }"></div>
    </div>

  <div class="controls">
    <el-button type="primary" round class="third" @click="toggleCameraSelection">
      选择摄像头
    </el-button>
    <el-button type="primary" round class="submit-atea-btn" @click="submitIntrusionArea">提交新的入侵区域</el-button>
  </div>

  <div class="controls" style="margin-top: 10px">
  <div class="button-extra">
    <el-select v-if="showCameraSelection"  class="select-btn" v-model="selectedCamera" placeholder="请选择机位">
      <el-option value="机位 1">1</el-option>
      <el-option value="机位 2">2</el-option>
      <el-option value="机位 3">3</el-option>
      <el-option value="机位 4">4</el-option>
    </el-select>
    <el-button v-if="showCameraSelection"  @click="submitCameraSelection">提交</el-button>
  </div>
  </div>


<!--  </div>-->
</template>

<script setup lang="ts">

import { ref,onMounted } from 'vue';
import { invadeCommitClick } from "@/api/video";
import { addWhiteList } from "@/api/InforManage";
import { recognize_close_click,invade_close_click, monitor_close_click, register_close_click, track_close_click } from "@/api/close";
import {ElButton, ElMessage} from "element-plus";
import { globalVariable } from '../../store/modules/globalurl'

/**
 * 钩子函数实时调用
 */
onMounted(async () => {
  await close(); // 调用你的函数
  checkVideoAvailability();
});

// const isVideoAvailable = (src: string) => {
//   return !!src;
// }

const isVideoAvailable = ref(false);

const checkVideoAvailability = async () => {
  try {
    const response = await fetch(videoSrc2.value);
    if (response.status === 200) {
      isVideoAvailable.value = true;
    } else {
      console.error('获取视频1信息失败，状态码：', response.status);
    }
  } catch (error) {
    console.error('发生错误：', error);
  }
};
async function close() {
  try {
    const responses = await Promise.all([
      register_close_click(),
      invade_close_click(),
      track_close_click(),
      monitor_close_click()
    ]);
    // Handle success for all requests
    responses.forEach(response => {
      var res = response.data;
      if (res.respCode !== '000000') {
        ElMessage.error(res.respMsg);
      }
    });
  } catch (error) {
    console.error(error);
    ElMessage.error('关闭失败，请重试');
  }
}//----------------------初始视频流-----------------------------
//----------------------初始视频流-----------------------------
const videoSrc2 = ref(globalVariable+'/api/video_invade/1');

const showCameraSelection = ref(false);
const selectedCamera = ref('');
const clickPositions = ref([]);
const commmitPositions = ref([]);
/**
 * 红点位置
 */
const videoContainerRef = ref(null);

function toggleCameraSelection() {
  showCameraSelection.value = !showCameraSelection.value;
  selectedCamera.value = '';
}

function submitCameraSelection() {

  let selectedCameraValue = selectedCamera.value; // 从 <select> 元素中获取选中的值

  if (selectedCameraValue === '1') {
    videoSrc2.value = globalVariable+'/api/video_invade/1';
    showCameraSelection.value = false;
    selectedCamera.value = '';
  } else if(selectedCameraValue === '2'){
    videoSrc2.value = globalVariable+'/api/video_invade/2';
    showCameraSelection.value = false;
    selectedCamera.value = '';
  } else if(selectedCameraValue === '3'){
    videoSrc2.value = globalVariable+'/api/video_invade/3';
    showCameraSelection.value = false;
    selectedCamera.value = '';
  } else if(selectedCameraValue === '4'){
    videoSrc2.value = globalVariable+'/api/video_invade/4';
    showCameraSelection.value = false;
    selectedCamera.value = '';
  }
}

function handleVideoClick(event) {
  /**
   * 相对路径的计算
   */
  const videoContainerRect = videoContainerRef.value.getBoundingClientRect();
  let offsetX = event.clientX - videoContainerRect.left;
  let offsetY = event.clientY - videoContainerRect.top;

  const position = {
    x: offsetX,
    y: offsetY
  };

  // 放入打点列表
  clickPositions.value.push(position);

  // 将 offsetY 转换为整数
  offsetX = Math.floor(offsetX);
  offsetY = Math.floor(offsetY);

  const commmitPosition = [offsetX, offsetY];

  // 放入接后端的列表
  commmitPositions.value.push(commmitPosition);

  console.log("鼠标左键点击位置：", position);
  console.log("当前列表： ", clickPositions.value);
  console.log("提交列表： ", commmitPosition.value);
}

/**
 * 钩子函数
 */
onMounted(() => {
  window.addEventListener('resize', () => {
    clickPositions.value = [];
  });
});
/**
 * 提交新的入侵区域函数
 */
function submitIntrusionArea() {
  console.log("提交入侵区域：", clickPositions.value);

  //提交和打点是两组变量
  const pointList = commmitPositions.value;
  const data = { pointList: pointList };

  invadeCommitClick(data)
      .then((response) => {

        var res = response.data

        if (res.success === true) {
          ElMessage.success('修改入侵区域成功');
          // router.push('/');
        }
        else {
          ElMessage.error(res.respMsg);
        }//else

      })//then
      .catch((error) => {
        console.error(error);
        ElMessage.error('修改入侵区域失败，请重试');
      });//catch

  //提交后清空
  clickPositions.value = [];
  commmitPositions.value= [];
}
</script>

<style scoped>
.container{
  //display: flex;
  //justify-content: center;
  //align-items: center;
  //height: 100vh;
  //flex-direction: column;
}
.video-container {
  display: grid;
  place-items: center;
  height: 70vh;
}
.video-stream {
  //width: 100%;
}

.controls {
  //margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  //margin-bottom: 50px;
}

.button-extra {
  display: flex;

}

.camera-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  margin-right: 10px;
}

.select-btn{
  margin-right: 10px;
  width: 180px;
}

.submit-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  margin-right: 10px;
}

.dot {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: red;
  border-radius: 50%;
}


.loader {
  -webkit-animation: spin 1s linear infinite;
  animation: spin 1s linear infinite;
  border: 30px solid #fff;
  border-bottom: 30px solid #E45A84;
  border-radius: 50%;
  width: 100px;
  height: 100px;
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(-360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(-360deg);
  }
}

h2 {
  animation: typing 1s infinite;
  font-size: 30px;
  margin-top: 30px;
  overflow: hidden;
}

@keyframes typing {
  from {
    width: 70%;
  }
  to {
    width: 100%;
  }
}

.video-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 750px;
  height: 500px;
  background-color: #3c5287;
  color: #333;
  font-size: 1.2em;
}

.third {
  border-color: $blue;
  color: #fff;
  box-shadow: 0 0 40px 40px $blue inset, 0 0 0 0 $blue;
  transition: all 150ms ease-in-out;

  &:hover {
    box-shadow: 0 0 10px 0 $blue inset, 0 0 10px 4px $blue;
  }
}

</style>